#include <std.h>
#include <vfb.h>
#include <text.h>
#include <memory.h>
#include <timer.h>
#include <irq.h>

#define VFB_SIZE 32768
#define SCREEN_LINES 16

unsigned char *vfb;
unsigned vcursor=0;

unsigned lcur=0;
static struct timer_call *vfb_update;


void text_update_timer()
{
	if(lcur!=vcursor)	{
		update_fb();
		lcur=vcursor;
	}
	update_timer(vfb_update,5);
}

void putcharv(int c)
{
	vfb[vcursor]=c;
	vcursor++;
}

void movecursorv(int pos)
{
	vcursor+=pos;
}	

/*This is the screen updater. This function is called when there is a change.*/
void update_fb()
{
	clrscr();
	unsigned s,line=0,screen_chars=0,c_in_line=0;
	for(s=vcursor;;s--)	{
		if(vfb[s]==10 || c_in_line>77)	{
			line++;
			c_in_line=0;
		} else
			c_in_line++;
		if(line>SCREEN_LINES)
			break;
		screen_chars++;
	}
	for(s=vcursor-screen_chars;vfb[s]!=0;s++)	{
		putchar_text(vfb[s]);
	}
	update_cursor();
}

void update_at(unsigned start)
{
	clrscr();
	unsigned s,line=0,screen_chars=0;
	for(s=vcursor;;s--)	{
		if(vfb[s]==10)
			line++;
		if(line>SCREEN_LINES)
			break;
		screen_chars++;
	}
	for(s=vcursor-screen_chars-start;s<vcursor-start;s++)	{
		putchar_text(vfb[s]);
	}
	update_cursor();
}

void init_textv()
{
	vcursor=0;
	vfb=(unsigned char *)get_mem(VFB_SIZE);
	memset(vfb,0,VFB_SIZE);
}

void init_updatefb()
{
	vfb_update=create_timer(text_update_timer,5);
}

void control_vfb(int k)
{
	static int pos=0;
	if(k==1)	{
		pos+=10;
		update_at(pos);
	} else if(k==2)	{
		pos-=10;
		update_at(pos);
	}
}
